package com.offcn.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.offcn.pojo.Menu;
import com.offcn.pojo.Permission;
import com.offcn.pojo.Role;
import com.offcn.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    //调用提供方
    @Reference
    private UserService userService;
    @Reference
    private RoleService roleService;
    @Reference
    private PermissionService permissionService;
    @Reference
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //登录
        User user = userService.getUserByName(username);
        if (user==null){
            throw new UsernameNotFoundException("用户名不正确");
        }
        System.out.println(user);
        List<GrantedAuthority> authorityList = new ArrayList<>();
        //查角色
        List<Role> roleList = roleService.listByRoleId(user.getId());
        if (roleList!=null && roleList.size()>0){
            for (Role role : roleList) {
                String keyword = role.getKeyword();
                if (!keyword.isEmpty()){
                    authorityList.add(new SimpleGrantedAuthority(keyword));
                }
            }
        }
        //查权限
        List<Permission> permissionList = permissionService.getPermissionById(user.getId());
        if (permissionList!=null && permissionList.size()>0){
            for (Permission permission : permissionList) {
                String keyword = permission.getKeyword();
                if (!keyword.isEmpty()){
                    authorityList.add(new SimpleGrantedAuthority(keyword));
                }
            }
        }
        //查菜单
        List<Menu> menuList = menuService.getMenuById(user.getId());
        if (menuList!=null && menuList.size()>0){
            for (Menu menu : menuList) {
                String path = menu.getLinkurl();
                if (!path.isEmpty()){
                    authorityList.add(new SimpleGrantedAuthority(path));
                }
            }
        }

        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorityList);
    }
}
